package ru.cjay.loading{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;


public class AssetLoader extends EventDispatcher {
    private var _name:String;
    private var _url:String;
    private var _handler:Function;
    private var _content:Object;

//    Флаг наличия процесса загрузки
    private var _progress:int = 0;
    private var _totalBytes:int = 0;
    private var _loadedBytes:int = 0;

    public function AssetLoader() {
    }

//    Вызывается при каждом кадре для подсчёта процента загруженного.
    private function onUpdate(event:ProgressEvent):void
    {
        var total:int = 0;
        var loaded:int = 0;

        _totalBytes     =event.bytesTotal;
        _loadedBytes    =event.bytesLoaded;
        _progress = loaded/total;
        event.stopImmediatePropagation();
        dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,true,true,_totalBytes,_loadedBytes));
    }

    public function loadFile(p_url:String, p_name:String=null, p_handler:Function = null):Object
    {
        _content = new Sprite();
        _url = p_url;
        _name = p_name;
        _handler = p_handler;

        var RM:ResourceManager = ResourceManager.getInstance();
        if (RM.hasResource(_url))
        {
            if (p_name) RM.addNameToURL(p_url, p_name);
            _content.addChild(RM.getResource(_url));

            if (_handler!=null){
                _handler(this.content);
            }
            dispatchEvent(new Event(Event.COMPLETE));
            return Object;
        }


        var request:URLRequest = new URLRequest(_url);
        SafeConnection.getInstance().makeSafe(request,onComplete,onUpdate,URLLoaderDataFormat.BINARY);
        return _content;
    }



    private function onComplete(event:Event):void
    {
        var newLoader:Loader = new Loader();
        newLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onNLoaderComplete,false, 0, true);
        newLoader.loadBytes(event.target.data);
        event.stopImmediatePropagation();
    }


    private function onNLoaderComplete(event:Event):void
    {
        var loaderInfo:LoaderInfo = event.target as LoaderInfo;
        var bm:DisplayObject = loaderInfo.content as DisplayObject;
//        var bm:Bitmap = loaderInfo.content as Bitmap;
//        bm.smoothing = true;

        _content.addChild(bm);

        var RM:ResourceManager = ResourceManager.getInstance();
//        RM.addImage(_url,bm,_name);
        RM.addResource(_url,bm,_name);


        if (_handler){
            _handler(this.content);
        }

        loaderInfo.removeEventListener(Event.COMPLETE, onNLoaderComplete);
        loaderInfo = null;

        event.stopImmediatePropagation();
        dispatchEvent(new Event(Event.COMPLETE));
    }

    public function get progress():int {
        return _progress;
    }


    public function get totalBytes():int {
        return _totalBytes;
    }

    public function get loadedBytes():int {
        return _loadedBytes;
    }


    public function get content():Object {
        return _content;
    }
}
}